package com.gzhryc.shared_device.oem.h5.agent.controllers.api.v1.place;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.api.DefaultAPIResponse;
import com.gzhryc.common.data.ValidateTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.base.models.OperateInfo;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentRelation;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentRelationBusinessConfig;
import com.gzhryc.shared_device.oem.code.agent.services.AgentRelationBusinessConfigService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentRelationService;
import com.gzhryc.shared_device.oem.code.business.EBusinessType;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlaceBusinessConfig;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlacePhysicalStore;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlaceProfitUser;
import com.gzhryc.shared_device.oem.code.place.dao.models.IncomeRatioContent;
import com.gzhryc.shared_device.oem.code.place.services.PlaceBusinessConfigService;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreService;
import com.gzhryc.shared_device.oem.code.place.services.PlaceProfitUserService;
import com.gzhryc.shared_device.oem.code.user.ERoleType;
import com.gzhryc.shared_device.oem.code.user.dao.db.User;
import com.gzhryc.shared_device.oem.code.user.services.UserService;
import com.gzhryc.shared_device.oem.h5.agent.ClientAPICodeConstants;
import com.gzhryc.shared_device.oem.h5.agent.LoginUser;
import com.gzhryc.shared_device.oem.h5.agent.WebConstants;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.place.PlaceProfitUserDelRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.place.PlaceProfitUserListRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.place.PlaceProfitUserListResponse;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.place.PlaceProfitUserSaveRequest;

/**
 * 网点用户相关接口，只代理角色使用
 */
public class PlaceUserController {

    @Route(value = "/agent/api/v1/place/user/list.data")
    public PlaceProfitUserListResponse userList(HttpServletRequest request){
        PlaceProfitUserListResponse apiResp = new PlaceProfitUserListResponse(ClientAPICodeConstants.NULL_DATA,"暂无数据");
        PlaceProfitUserListRequest apiReq = WebUtils.getJsonRequest(request,PlaceProfitUserListRequest.class);
        if(apiReq != null && apiReq.getBody().getPlaceId() != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null && ERoleType.Agent.index().equals(loginUser.getRoleType())) {
                PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(apiReq.getBody().getPlaceId());
                if (physicalStore != null && physicalStore.getUserId().equals(loginUser.getId())) {
                    //先添加代理
                    PlaceProfitUserListResponse.UserItem placeUserItem = new PlaceProfitUserListResponse.UserItem();
                    placeUserItem.setUserId(loginUser.getId());
                    placeUserItem.setUserName(loginUser.getNickname());
                    placeUserItem.setUserPhone(loginUser.getPhone());
                    placeUserItem.setRoleType(ERoleType.Agent.index());
                    placeUserItem.setRoleTypeName(ERoleType.Agent.note());
                    placeUserItem.setCreateDate(physicalStore.getCreateDate());

                    //网点是当前用户创建的
                    apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                    apiResp.getBody().setUserItems(new ArrayList<>());
                    apiResp.getBody().getUserItems().add(placeUserItem);
                    
                    List<PlaceBusinessConfig> placeBusiConfigList = PlaceBusinessConfigService.self().findByPlaceId(physicalStore.getId());

                    Map<String, Double> incomeRatioData = new HashMap<>();      //分成信息

                    List<PlaceProfitUser> placeProfitUserList = PlaceProfitUserService.self().findJoinByPlaceId(apiReq.getBody().getPlaceId());
                    if (placeProfitUserList != null && placeProfitUserList.size() > 0) {
                        for (PlaceProfitUser profitUser : placeProfitUserList) {
                            PlaceProfitUserListResponse.UserItem userItem = new PlaceProfitUserListResponse.UserItem();
                            userItem.setUserId(profitUser.getUserId());
                            userItem.setUserName(profitUser.getUser().getName());
                            userItem.setUserPhone(profitUser.getUser().getPhone());
                            userItem.setRoleType(profitUser.getRoleType());
                            userItem.setRoleTypeName(profitUser.getRoleTypeName());
                            userItem.setNote(profitUser.getNote());
                            userItem.setCreateDate(profitUser.getCreateDate());
                            
                            List<PlaceProfitUserListResponse.IncomeRatioItem> incomeRationItems = new ArrayList<>();
                            
                            if(ERoleType.Partner.index().equals(profitUser.getRoleType())) {
                            	List<AgentRelationBusinessConfig> arBusiConfigList = AgentRelationBusinessConfigService.self().findByUserKeys(profitUser.getPlaceUserId()
                            			, profitUser.getUserId());
                            	if(arBusiConfigList != null && arBusiConfigList.size() > 0) {
                            		for(AgentRelationBusinessConfig busiConfig : arBusiConfigList) {
	                            		PlaceProfitUserListResponse.IncomeRatioItem incomeRatioItem = new PlaceProfitUserListResponse.IncomeRatioItem();
	                                    incomeRatioItem.setBusinessType(busiConfig.getBusinessType());
	                                    incomeRatioItem.setBusinessTypeName(busiConfig.getBusinessTypeName());
	                                    incomeRatioItem.setIncomeRatio(busiConfig.getIncomeRatio());
	                                    incomeRationItems.add(incomeRatioItem);
                            		}
                            	}
                            }

                            if (StringTools.isNotBlank(profitUser.getIncomeRatioContent())) {
                                IncomeRatioContent incomeRatioContent = JsonTools.fromJson(profitUser.getIncomeRatioContent(), IncomeRatioContent.class);
                                for (IncomeRatioContent.Item item : incomeRatioContent.getItems()) {
                                    PlaceProfitUserListResponse.IncomeRatioItem incomeRatioItem = new PlaceProfitUserListResponse.IncomeRatioItem();
                                    incomeRatioItem.setBusinessType(item.getBusinessType());
                                    incomeRatioItem.setBusinessTypeName(EBusinessType.note(item.getBusinessType()));
                                    incomeRatioItem.setIncomeRatio(item.getIncomeRatio());
                                    incomeRationItems.add(incomeRatioItem);

                                    Double incomeRatio = incomeRatioData.get(item.getBusinessType());
                                    if (incomeRatio == null) {
                                        incomeRatio = 0.0;
                                    }
                                    incomeRatio = incomeRatio + item.getIncomeRatio();
                                    incomeRatioData.put(item.getBusinessType(), incomeRatio);
                                }
                            }
                            
                            if(incomeRationItems.size() > 0) {
                            	userItem.setIncomeRatioItems(new ArrayList<>());
                            	if(placeBusiConfigList != null && placeBusiConfigList.size() > 0) {
	                            	for(PlaceBusinessConfig placeBusiConfig : placeBusiConfigList) {
	                            		boolean flag = true;
	                                	for(PlaceProfitUserListResponse.IncomeRatioItem incomeRatioItem : incomeRationItems) {
	                                		if(incomeRatioItem.getBusinessType().equals(placeBusiConfig.getBusinessType())) {
	                                			userItem.getIncomeRatioItems().add(incomeRatioItem);
	                                			flag = false;
	                                			break;
	                                		}
	                                	}
	                                	if(flag) {
	                                		PlaceProfitUserListResponse.IncomeRatioItem incomeRatioItem = new PlaceProfitUserListResponse.IncomeRatioItem();
	                                        incomeRatioItem.setBusinessType(placeBusiConfig.getBusinessType());
	                                        incomeRatioItem.setBusinessTypeName(placeBusiConfig.getBusinessTypeName());
	                                        incomeRatioItem.setIncomeRatio(0D);
	                                        userItem.getIncomeRatioItems().add(incomeRatioItem);
	                                	}
	                                }
                            	}
                            }
                            apiResp.getBody().getUserItems().add(userItem);
                        }
                    }

                    if (incomeRatioData.size() > 0) {
                    	List<PlaceProfitUserListResponse.IncomeRatioItem> incomeRationItems = new ArrayList<>();
                    	
                        if (placeUserItem.getIncomeRatioItems() == null) {
                            placeUserItem.setIncomeRatioItems(new ArrayList<>());
                        }
                        
                        for (String businessType : incomeRatioData.keySet()) {
                            boolean flag = true;
                            for (PlaceProfitUserListResponse.IncomeRatioItem item : placeUserItem.getIncomeRatioItems()) {
                                if (businessType.equals(item.getBusinessType())) {
                                    flag = false;
                                    break;
                                }
                            }

                            if (flag) {
                                PlaceProfitUserListResponse.IncomeRatioItem incomeRatioItem = new PlaceProfitUserListResponse.IncomeRatioItem();
                                incomeRatioItem.setBusinessType(businessType);
                                incomeRatioItem.setBusinessTypeName(EBusinessType.note(businessType));
                                incomeRatioItem.setIncomeRatio(100D);

                                Double incomeRatio = incomeRatioData.get(businessType);
                                if (incomeRatio != null) {
                                    Double temp = 100.0 - incomeRatio;
                                    if (temp > 0) {
                                        incomeRatioItem.setIncomeRatio(temp);
                                    } else {
                                        incomeRatioItem.setIncomeRatio(0D);
                                    }
                                }
                                incomeRationItems.add(incomeRatioItem);
                            }
                        }
                        
                        if(placeBusiConfigList != null && placeBusiConfigList.size() > 0) {
	                        for(PlaceBusinessConfig placeBusiConfig : placeBusiConfigList) {
	                    		boolean flag = true;
	                        	for(PlaceProfitUserListResponse.IncomeRatioItem incomeRatioItem : incomeRationItems) {
	                        		if(incomeRatioItem.getBusinessType().equals(placeBusiConfig.getBusinessType())) {
	                        			placeUserItem.getIncomeRatioItems().add(incomeRatioItem);
	                        			flag = false;
	                        			break;
	                        		}
	                        	}
	                        	if(flag) {
	                        		PlaceProfitUserListResponse.IncomeRatioItem incomeRatioItem = new PlaceProfitUserListResponse.IncomeRatioItem();
	                                incomeRatioItem.setBusinessType(placeBusiConfig.getBusinessType());
	                                incomeRatioItem.setBusinessTypeName(placeBusiConfig.getBusinessTypeName());
	                                incomeRatioItem.setIncomeRatio(100D);
	                                placeUserItem.getIncomeRatioItems().add(incomeRatioItem);
	                        	}
	                        }
                        }
                    }else {
                    	if(placeBusiConfigList != null && placeBusiConfigList.size() > 0) {
                    		if (placeUserItem.getIncomeRatioItems() == null) {
                                placeUserItem.setIncomeRatioItems(new ArrayList<>());
                            }
	                        for(PlaceBusinessConfig placeBusiConfig : placeBusiConfigList) {
                        		PlaceProfitUserListResponse.IncomeRatioItem incomeRatioItem = new PlaceProfitUserListResponse.IncomeRatioItem();
                                incomeRatioItem.setBusinessType(placeBusiConfig.getBusinessType());
                                incomeRatioItem.setBusinessTypeName(placeBusiConfig.getBusinessTypeName());
                                incomeRatioItem.setIncomeRatio(100D);
                                placeUserItem.getIncomeRatioItems().add(incomeRatioItem);
	                        }
                        }
                    }
                } else {
                    apiResp.setCode(ClientAPICodeConstants.NOT_POWER, "无权限查看");
                }
            } else {
                apiResp.setCode(ClientAPICodeConstants.NOT_POWER, "无权限查看");
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/place/user/save.do")
    public DefaultAPIResponse doSave(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR, "保存分成用户失败");
        PlaceProfitUserSaveRequest apiReq = WebUtils.getJsonRequest(request, PlaceProfitUserSaveRequest.class);
        if (apiReq != null && apiReq.getBody().getPlaceId() != null && StringTools.isNotBlank(apiReq.getBody().getPhone()) && apiReq.getBody().getRoleType() != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null && ERoleType.Agent.index().equals(loginUser.getRoleType())) {
                if (!ValidateTools.isPhone(apiReq.getBody().getPhone())) {
                    apiResp.setMsg("手机号不正确，请检查");
                    return apiResp;
                }

                PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(apiReq.getBody().getPlaceId());
                if(physicalStore == null){
                    apiResp.setMsg("未找到网点信息");
                    return apiResp;
                }

                if(!physicalStore.getUserId().equals(loginUser.getId())){
                    apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限操作");
                    return apiResp;
                }

                User user = UserService.self().getByPhone(apiReq.getBody().getPhone());
                if (user == null) {
                    if (StringTools.isBlank(apiReq.getBody().getName())) {
                        apiResp.setMsg("用户不存在，请填写用户姓名");
                        return apiResp;
                    }
                    user = new User();
                    user.setName(apiReq.getBody().getName());
                    user.setPhone(apiReq.getBody().getPhone());
                    user.setReferrerId(loginUser.getId());
                    user.setReferrerName(loginUser.getFullName());
                }else {
	                if(ERoleType.Partner.index().equals(apiReq.getBody().getRoleType())) {
	                	AgentRelation agentRelation = AgentRelationService.self().getByKeys(loginUser.getId(), user.getId());
	                	if(agentRelation != null && !ERoleType.Partner.index().equals(agentRelation.getRoleType())) {
	                		apiResp.setMsg("用户不是合伙人角色");
	                        return apiResp;
	                	}
	                }
                }

                PlaceProfitUser placeProfitUser = new PlaceProfitUser();
                placeProfitUser.setPlaceId(apiReq.getBody().getPlaceId());
                placeProfitUser.setUserId(user.getId());
                placeProfitUser.setRoleType(apiReq.getBody().getRoleType());
                placeProfitUser.setNote(apiReq.getBody().getNote());

                IncomeRatioContent incomeRatioContent = null;
                if(apiReq.getBody().getIncomeRatioMap() != null && apiReq.getBody().getIncomeRatioMap().size() > 0) {
                    incomeRatioContent = new IncomeRatioContent();
                    for (String businessType : apiReq.getBody().getIncomeRatioMap().keySet()) {
                        Double incomeRadio = apiReq.getBody().getIncomeRatioMap().get(businessType);
                        if (incomeRadio != null) {
                            if (incomeRadio >= 0 && incomeRadio <= 100) {
                                IncomeRatioContent.Item item = new IncomeRatioContent.Item();
                                item.setBusinessType(businessType);
                                item.setIncomeRatio(incomeRadio);
                                incomeRatioContent.getItems().add(item);
                            } else {
                                apiResp.setMsg(EBusinessType.note(businessType) + "分成设置错误");
                                return apiResp;
                            }
                        }
                    }
                }

                PlaceProfitUser temp = PlaceProfitUserService.self().getByKeys(apiReq.getBody().getPlaceId(),user.getId());
                if(temp == null) {
                	OperateInfo operateInfo = new OperateInfo(WebConstants.PROGRAM_TYPE, WebConstants.PROGRAM_TYPE_NAME);
                    operateInfo.setOperator(loginUser.getRoleType(), loginUser.getFullName());
                    operateInfo.setOperatorId(loginUser.getId());
                	
                    try {
                        if (PlaceProfitUserService.self().add(physicalStore,placeProfitUser, user, incomeRatioContent,operateInfo)) {
                            apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                        }
                    } catch (LogicException e) {
                        apiResp.setMsg(e.getMessage());
                    }
                }else{
                    try {
                        if (PlaceProfitUserService.self().updateNotNull(placeProfitUser, incomeRatioContent)) {
                            apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                        }
                    } catch (LogicException e) {
                        apiResp.setMsg(e.getMessage());
                    }
                }
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/place/user/del.do")
    public DefaultAPIResponse doDelUser(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR, "删除分成用户失败");
        PlaceProfitUserDelRequest apiReq = WebUtils.getJsonRequest(request, PlaceProfitUserDelRequest.class);
        if (apiReq != null && apiReq.getBody().getPlaceId() != null && apiReq.getBody().getUserId() != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null && ERoleType.Agent.index().equals(loginUser.getRoleType())) {
                try {
                    if (PlaceProfitUserService.self().deleteByKeys(apiReq.getBody().getPlaceId(), apiReq.getBody().getUserId())) {
                        apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                    }
                } catch (LogicException e) {
                    apiResp.setMsg(e.getMessage());
                }
            }
        }
        return apiResp;
    }
}
